package com.android.lovely.ui.activity

import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.cachedIn
import com.android.lovely.R
import com.android.lovely.api.service.systemService
import com.android.lovely.api.service.userService
import com.android.lovely.data.SysMsg
import com.android.lovely.databinding.ActivitySysMsgBinding
import com.android.lovely.ext.init
import com.android.lovely.ext.windowBackgroundNav
import com.android.lovely.ext.windowBackgroundStatus
import com.android.lovely.framework.BaseActivity
import com.android.lovely.framework.BasePageSource
import com.android.lovely.framework.launchWithLoading
import com.android.lovely.ui.adapter.SysMsgAdapter
import com.android.lovely.ui.dialog.showLovelyDialog
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.withContext

class SysMsgActivity : BaseActivity<ActivitySysMsgBinding>() {

    private val adapter by lazy { SysMsgAdapter() }

    private val pager by lazy {
        Pager(PagingConfig(
            pageSize = 10,
            initialLoadSize = 10
        ), pagingSourceFactory = { SysPagingSource() }).flow.cachedIn(lifecycleScope)
    }

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.flTop.addStatusBarMarginTop()
        mBinding.list.adapter = adapter
        mBinding.back.clickable { onBackPressedDispatcher.onBackPressed() }
        mBinding.srlRefresh.init()
        mBinding.flex.setNoContentIcon(R.drawable.msg_empty)
        mBinding.flex.setNoContentText(getString(R.string.msg_empty))
        mBinding.flex.setLoadState(adapter)
        mBinding.srlRefresh.setOnRefreshListener {
            adapter.refresh()
        }
        lifecycleScope.launchSafety {
            pager.collectLatest {
                adapter.submitData(it)
            }
        }
        adapter.addOnPagesUpdatedListener { mBinding.srlRefresh.isRefreshing = false }
        adapter.onDeleteClick = { id ->
            showLovelyDialog {
                setDialogTitle(getString(R.string.delete_msg))
                setPositiveButton { delete(id) }
            }
        }
        mBinding.unreadCount.clickable {
            lifecycleScope.launchWithLoading {
                userService.readAllPush()
                mBinding.unreadCount.text = "0"
                mBinding.unreadCount.isSelected = false
                mBinding.srlRefresh.isRefreshing = true
                adapter.refresh()
            }
        }
        adapter.onItemClick = {
            startPage<MsgActivity>("msg" to it)
        }
    }

    private inner class SysPagingSource : BasePageSource<SysMsg>() {
        override suspend fun getResponse(page: Int, loadSize: Int): List<SysMsg> =
            withContext(Dispatchers.IO) {
                return@withContext userService.getSysMsg(
                    mapOf(
                        "page" to page, "size" to loadSize
                    )
                ).getOrDefault("list", emptyList())
            }

        override fun dataChange(data: SysMsg) {

        }
    }

    private fun requestUnreadCount() {
        lifecycleScope.launchSafety {
            val count = systemService.getUnreadMsg().getOrDefault("unread_num", 0)
            if (count > 0) {
                mBinding.unreadCount.text = if (count < 100) count.toString() else "99+"
            } else {
                mBinding.unreadCount.text = "0"
            }
            mBinding.unreadCount.isSelected = count > 0
        }
    }

    private fun delete(id: Int) {
        lifecycleScope.launchWithLoading {
            userService.deleteSystemPush(mapOf("id" to id))
            mBinding.srlRefresh.isRefreshing = true
            adapter.refresh()
        }
    }

    override fun onResume() {
        super.onResume()
        requestUnreadCount()
    }

}